package com.kitty.common.start;

import com.kitty.common.cache.entity.AppProperties;
import com.kitty.common.utils.SpringUtils;
import com.kitty.cross.login.service.CrossService;
import com.kitty.game.ProductDataPool;
import com.kitty.game.ServerService;
import com.kitty.game.activity.service.shidao.ShiDaoHandler;
import com.kitty.game.activity.service.time.XingGuanHandler;
import com.kitty.game.artifact.ArtifactService;

import com.kitty.game.bag.model.GiftBagData;
import com.kitty.game.config.*;
import com.kitty.game.equip.EquipDataPool;
import com.kitty.game.equip.handler.EquipHunQiFenHuaHandler;
import com.kitty.game.equip.service.*;
import com.kitty.game.fuling.FulingInfo;
import com.kitty.game.gm.GmService;
import com.kitty.game.map.service.MapService;
import com.kitty.game.npc.NpcDataPool;
import com.kitty.game.onlinemall.service.MallService;
import com.kitty.game.party.service.PartyService;
import com.kitty.game.pet.service.PetService;
import com.kitty.game.rank.service.RankService;
import com.kitty.game.scene.SceneManager;
import com.kitty.game.school.service.SchoolService;
import com.kitty.game.shidao.KuafuShidaoService;
import com.kitty.game.shop.ShopDataPool;
import com.kitty.game.task.TaskDataPool;
import com.kitty.game.task.service.taskHandler.DugeonTaskHandler;
import com.kitty.game.utils.ProtocalSet;
import com.kitty.mina.Modules;
import com.kitty.mina.cache.DataCache;
import com.kitty.web.system.gameServer.GameServerRefresh;
import lombok.extern.slf4j.Slf4j;
import org.nutz.dao.Cnd;
import org.nutz.dao.Dao;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

import java.util.*;


@Component
@Slf4j
public class MyApplicationRunner implements ApplicationRunner {


    @Autowired
    Dao dao;
    @Autowired
    ArtifactService artifactService;
    String inetIp;
    String ceshi;

    @Override
    public void run(ApplicationArguments var1) {
        //初始化对话
        initTotal();

//        SpringUtils.getBean(XingGuanHandler.class).flushXingGuanAfterServerStart();
        SpringUtils.getBean(ServerService.class).init();
        SpringUtils.getBean(GmService.class).init();
        SpringUtils.getBean(DWDRService.class).init();
        SpringUtils.getBean(HDDSService.class).init();
        SpringUtils.getBean(KuafuShidaoService.class).init();
        SpringUtils.getBean(DLTService.class).init();
        SpringUtils.getBean(ShuadaoService.class).init();
        SpringUtils.getBean(EquipHunQiFenHuaHandler.class).init();
//        SpringUtils.getBean(ServerService.class).getScheduledExecutorService().schedule(new Runnable() {
//            @Override
//            public void run() {
//                SpringUtils.getBean(SuperBossHandler.class).flushBoss();
//                SpringUtils.getBean(SuperBossHandler.class).flushBoss1();
//            }
//        },60, TimeUnit.SECONDS);
      //首次称号的，不要可以注释掉
        // SpringUtils.getBean(GameUtil.class).loadCommonSet();
        SpringUtils.getBean(TZLCService.class).init();
    }

    public void initTotal() {
        log.warn("初始化游戏配置数据...");
        // 初始化每日签到奖励数据
        initDaySign();
        //初始化宠物兑换
        initExChangePet();
        //野生宠物商店
        initPetShop();
        // 初始化药品
        initMedicine();
        // 初始化特殊物品
        initSpecialItem();
        // 初始化装备信息
        initEquip();
        // 初始化技能数据
        initSkill();
        // 初始化宠物人物经验等级
        initExp();
        //初始化地图传送点
        initTrasfer();
        // 初始化地图数据
        initMap();
        // 初始化npc数据
        initNpc();
        // 初始化抽奖数据
        initChoujiang();
        // 初始化服务器信息
        initServer();
        // 初始化怪物
        initMonster();
        //初始化商城道具
        initOnlineMall();
        //初始化时装
        initFasion();
        //初始化时装外观Icon
        initFasionIcon();
        //初始化自定义时装
        initCustomFasion();
        // 初始化法宝数据
        artifactService.initArtifactExp();
        // 初始化星数据
        SpringUtils.getBean(XingGuanHandler.class).loadXingGuanSet();
        // 初始化新手礼包
        initNewcomerGift();
        // 初始化礼包数据
        initGiftBagData();

        initProtocal();

        ProductDataPool.INSTANCE.load();

        initCommonData();

        /**加载已有帮派*/
        SpringUtils.getBean(PartyService.class).loadParty();

        TaskDataPool.initType2Handler();

        FulingInfo.loadFulingzhen();//附灵
        //加载挑战次数
        SpringUtils.getBean(GameServerRefresh.class).refreshCache("refreshBossNumInfo","","");

        // 启动跨服
        SpringUtils.getBean(CrossService.class).init();
        SpringUtils.getBean(ZHJService.class).init();
        SpringUtils.getBean(GSGService.class).init();
        //SpringUtils.getBean(ChargeActivityService.class).init();

    }


    public void initNewcomerGift() {
        DataCache.NEWCOMER_GIFT.clear();
        List<NewcomerGift> list = dao.query(NewcomerGift.class, Cnd.NEW());
        for (NewcomerGift newcomerGift : list) {
            List<NewcomerGift> newcomerGifts = DataCache.NEWCOMER_GIFT.computeIfAbsent(newcomerGift.getGetLevel(), k -> new ArrayList<>());
            newcomerGifts.add(newcomerGift);
        }
        log.info("初始化新手礼包");
    }

    public void initExChangePet() {
        List<ExchangePet> petList = new ArrayList<>();
        {
            List<AppProperties> list = dao.query(AppProperties.class, Cnd.where("classtype","=","ExChangeBy").asc("id"));
            for (AppProperties appProperties : list) {
                ExchangePet exchangePet = new ExchangePet();
                exchangePet.setName(appProperties.getType_());
                exchangePet.setNum(Integer.parseInt(appProperties.getValue_()));
                exchangePet.setType((byte)1);
                petList.add(exchangePet);
            }
        }
        {
            List<AppProperties> list = dao.query(AppProperties.class, Cnd.where("classtype","=","ExChangeSh").asc("id"));
            for (AppProperties appProperties : list) {
                ExchangePet exchangePet = new ExchangePet();
                exchangePet.setName(appProperties.getType_());
                exchangePet.setNum(Integer.parseInt(appProperties.getValue_()));
                exchangePet.setType((byte)2);
                petList.add(exchangePet);
            }
        }
        PetService bean = SpringUtils.getBean(PetService.class);
        bean.initExChangePet(petList);
    }

    public void initCustomFasion() {
        DataCache.NAME_CUSTOMFASION.clear();
        List<CustomFasion> list = dao.query(CustomFasion.class, Cnd.NEW());
        for (CustomFasion customFasion : list) {
            DataCache.NAME_CUSTOMFASION.put(customFasion.getName(), customFasion);
        }
    }

    public void initFasionIcon() {
        List<FasionIcon> list = dao.query(FasionIcon.class, Cnd.NEW());
        DataCache.ICON_FASION.clear();
        for (FasionIcon fasionIcon : list) {
            DataCache.ICON_FASION.put(fasionIcon.getIcon(), fasionIcon.getFasionIcon());
        }
    }

    public void initFasion() {
        DataCache.NAME_FASION.clear();
        List<Fasion> list = dao.query(Fasion.class, Cnd.NEW());
        for (Fasion fasion : list) {
            DataCache.NAME_FASION.put(fasion.getName(), fasion);

        }
    }


    public void initChoujiang() {
        DataCache.LOTTERYS.clear();
        List<ChoujiangGift> list = dao.query(ChoujiangGift.class, Cnd.NEW().asc("id"));
        int nomal = 0;
        int dae = 0;
        for (ChoujiangGift choujiangGift:list){
            nomal = choujiangGift.getNormal()+nomal;
            dae = dae+choujiangGift.getDae();
        }
        log.error("抽奖普通=={}==大额=={}",nomal,dae);
        DataCache.LOTTERYS.addAll(list);
    }

    public void initDaySign() {
        DataCache.ID_DAYSIGN.clear();
        List<AppProperties> list = dao.query(AppProperties.class, Cnd.where("classtype","=","meiriqiandao").asc("id"));
        for (int i = 0; i < 31; i++) {//原先写的32  改成31看会不会有bug
            AppProperties appProperties = list.get(i);
            String type_ = appProperties.getValue_();
            String[] split = type_.split("-");
            DaySign daySign =new DaySign();
            daySign.setName(split[1]);
            daySign.setNum(Integer.parseInt(split[2]));
            DataCache.ID_DAYSIGN.put(i+1, daySign);
        }
    }




    public void initPetShop() {
        List<PetShop> list = dao.query(PetShop.class, Cnd.NEW());
        ShopDataPool.initPetShopData(list);
    }


    private void initMedicine() {
        List<Medicine> list = dao.query(Medicine.class, Cnd.NEW());
        ShopDataPool.initMedicineData(list);
    }


    private void initSpecialItem() {
        List<SpecialItem> list = dao.query(SpecialItem.class, Cnd.NEW());
        SpringUtils.getBean(MallService.class).initSpecialItem(list);
    }

    public void initMonster() {
        List<PetSet> list = dao.query(PetSet.class, Cnd.NEW());
        DataCache.MOUNTS.clear();
        DataCache.ICON_PETSET.clear();
        DataCache.NAME_ICON.clear();
        DataCache.VARIATION.clear();
        for (PetSet petSet : list) {
            DataCache.ICON_PETSET.put(petSet.getIcon(), petSet);
            DataCache.NAME_ICON.put(petSet.getName(), petSet.getIcon());
            if (petSet.getType() == 1) {
                DataCache.MOUNTS.add(petSet.getName());
            }
            if (petSet.getType1() == 3) {
                DataCache.VARIATION.add(petSet.getName());
            }
        }

    }

    private void initEquip() {
        List<Equip> list = dao.query(Equip.class, Cnd.NEW());
        EquipDataPool.initEquipData(list);
    }

    private void initExp() {
        List<RoleExp> list = dao.query(RoleExp.class, Cnd.NEW());
        List<PetExp> petExps = dao.query(PetExp.class, Cnd.NEW());
        SpringUtils.getRoleService().initUpgradeNeedExp(list);
        SpringUtils.getRoleService().initPetUpgradeNeedExp(petExps);
    }

    private void initSkill() {
        List<Skill> list = dao.query(Skill.class, Cnd.NEW());
        SpringUtils.getSkillService().initSkill(list);
    }


    public void initServer() {
        List<Server> list = dao.query(Server.class, Cnd.NEW().orderBy("id", "asc"));
        DataCache.ID_SERVER.clear();
        for (Server server : list) {
            DataCache.ID_SERVER.put(server.getId(), server);
        }
    }


    /**
     * 初始化礼包数据
     */
    private void initGiftBagData() {
        List<GiftBagData> list = dao.query(GiftBagData.class, Cnd.NEW().orderBy("id", "asc"));
        DataCache.GIFT_BAG_DATA_MAP.clear();
        Map<String, List<GiftBagData>> map = new HashMap<>();
        for (GiftBagData giftBagData : list) {
            List<GiftBagData> tmpList = new ArrayList<>();
            if (map.containsKey(giftBagData.getName())) {
                tmpList.addAll(map.get(giftBagData.getName()));
            }
            tmpList.add(giftBagData);
            map.put(giftBagData.getName(), tmpList);
        }
        DataCache.GIFT_BAG_DATA_MAP.putAll(map);

        //初始化使用药品信息
        DataCache.USE_BAG_DATA_MAP.put("潜金散", 1);
        DataCache.USE_BAG_DATA_MAP.put("神木丸", 2);
        DataCache.USE_BAG_DATA_MAP.put("柔水丹", 3);
        DataCache.USE_BAG_DATA_MAP.put("烈火散", 4);
        DataCache.USE_BAG_DATA_MAP.put("三土丸", 5);
    }

    public void initNpc() {
        List<NPC> list = dao.query(NPC.class, Cnd.NEW());
        DataCache.ID_NPC.clear();
        DataCache.NAME_NPCID.clear();
        DataCache.MAP_NPCIDS.clear();

        for (NPC npc : list) {
            if (npc.getType() == NPC.TYPE_TASK) {
                NpcDataPool.taskNpcMap.put(npc.getId(), npc);
            } else if (npc.getType() == NPC.TYPE_TASK_SCHOOL) {
                SpringUtils.getBean(SchoolService.class).initTaskSchoolNpc(npc);
            } else {
                DataCache.ID_NPC.put(npc.getId(), npc);
                DataCache.NAME_NPCID.put(npc.getName(), npc.getId());
                Set<Integer> set = DataCache.MAP_NPCIDS.computeIfAbsent(npc.getMapId(), k -> new HashSet<>());
                set.add(npc.getId());
            }

        }
    }

    private void initTrasfer() {
        List<Transfer> list = dao.query(Transfer.class, Cnd.NEW());
        SpringUtils.getMapService().initTrasfer(list);
    }

    private void initMap() {
        List<GameMap> gameMaps = dao.query(GameMap.class, Cnd.NEW());
        SpringUtils.getBean(MapService.class).initMapInfo(gameMaps);
        SceneManager.INSTANCE.initiate(gameMaps);

    }

    private void initProtocal() {
        // 登录游戏协议
        ProtocalSet.loginSet.add(Modules.CMD_LOGIN);
        ProtocalSet.loginSet.add(Modules.CMD_L_LINE_DATA);
        ProtocalSet.loginSet.add(Modules.CMD_ECHO);
        ProtocalSet.loginSet.add(Modules.CMD_CREATE_NEW_CHAR);
        ProtocalSet.loginSet.add(Modules.CMD_LOAD_EXISTED_CHAR);
        ProtocalSet.loginSet.add(Modules.CMD_L_REQUEST_LINE_INFO);
        ProtocalSet.loginSet.add(Modules.CMD_L_ACCOUNT);
        ProtocalSet.loginSet.add(Modules.CMD_RANDOM_NAME);
        ProtocalSet.loginSet.add(Modules.CMD_OPER_SCENARIOD);
        ProtocalSet.loginSet.add(Modules.CMD_L_GET_COMMUNITY_ADDRESS);
        ProtocalSet.loginSet.add(Modules.CMD_L_LOGIN_PREVIEW_PLAYER);
        ProtocalSet.loginSet.add(Modules.CMD_GENERAL_NOTIFY);
    }

    /**
     * 初始化在线商城
     */
    public void initOnlineMall() {
        DataCache.NUM_MALL.clear();
        DataCache.NAME_MALL.clear();
        List<OnlineMall> list = dao.query(OnlineMall.class, Cnd.NEW());
        for (OnlineMall onlineMall : list) {
            DataCache.NUM_MALL.put(onlineMall.getNumber(), onlineMall);
            DataCache.NAME_MALL.put(onlineMall.getName(), onlineMall);
        }
    }

    /**
     * 初始化公共数据
     */
    public void initCommonData() {
        //是否加载排行榜信息
        //不是测试的时候在加载

            RankService rankService = SpringUtils.getBean(RankService.class);
            rankService.init();


//        SpringUtils.getBean(NewHelpActivityHandler.class).init();

        SpringUtils.getMirrorService().loadFightMirrors();
        SpringUtils.getBean(ShiDaoHandler.class).loadCommon();
      //  SpringUtils.getBean(RechargeScoreRewardHandler.class).loadHistory();
        SpringUtils.getFriendService().loadCommon();
        SpringUtils.getBean(DugeonTaskHandler.class).loadCommon();

        SpringUtils.getPartyService().loadCommon();
    }
}